<?php

namespace App\User\Controllers;

use Ichynul\LaADuo\LaADuoExt;
use Illuminate\Http\Request;
use Encore\Admin\Controllers\AuthController as BaseAuthController;

class AuthController extends BaseAuthController
{
    
    /**
     * Handle a login request.
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function postLogin(Request $request)
    {
        $this->loginValidator($request->all())->validate();
		$username = $request->input('username');

        $map = [
            'email' => filter_var($username, FILTER_VALIDATE_EMAIL),
            'mobile' => $this->validateChinaPhoneNumber($username),
        ]; 
		$field=key(array_filter($map)) ?? 'username';

		$request->merge([
            $field => $username,
        ]);       


        $credentials = $request->only([$field, 'password']);
        $remember = $request->get('remember', false);


        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return back()->withInput()->withErrors([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }	


    protected function validateChinaPhoneNumber($number)
    {
        return preg_match('/^1[34578]\d{9}$/', $number);
    }

	
	/**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return LaADuoExt::guard();
    }
}